package com.mjlf.nio.chat;


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioClient {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        if(socketChannel.connect(new InetSocketAddress("127.0.0.1", 8013))){
            socketChannel.register(selector, SelectionKey.OP_READ);
        }else {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }

        while (true){
            selector.select(2000);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                SelectionKey key = iterator.next();

                if(key.isValid()){
                    if(key.isConnectable()){
                        SocketChannel channel = (SocketChannel)key.channel();
                        if(channel.finishConnect()){
                            channel.register(selector, SelectionKey.OP_READ);
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            byteBuffer.put("hello".getBytes());
                            byteBuffer.flip();
                            channel.write(byteBuffer);
                        }else {
                            System.out.println("again");
                        }
                    }else if(key.isReadable()){
                        SocketChannel channel = (SocketChannel)key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        System.out.println(new String(byteBuffer.array()));
                    }
                }
                selectionKeys.remove(key);
            }
        }
    }
}
